#include "stdafx.h"

#include "RectElement.h"

const DWORD RECT_VERTEX::dwFVF = D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1;
//const DWORD RECT_VERTEX::dwFVF = D3DFVF_XYZ | D3DFVF_TEX1;

RectElement::RectElement()
:m_pVertexBuffer(NULL)
,m_pTexture(NULL)
,m_Color(0xffffffff)
{}

RectElement::~RectElement()
{}

bool RectElement::Create(LPDIRECT3DDEVICE9 pd3dDevice)
{
	assert(m_pVertexBuffer == NULL && m_pTexture == NULL && pd3dDevice != NULL);

	if( FAILED( pd3dDevice->CreateVertexBuffer( 6 * sizeof( RECT_VERTEX ),
		0, RECT_VERTEX::dwFVF,
		D3DPOOL_DEFAULT, &m_pVertexBuffer, NULL ) ) )
	{
		return false;
	}

	return true;
}

void RectElement::Release()
{
	if( m_pVertexBuffer != NULL )
	{
		m_pVertexBuffer->Release();
		m_pVertexBuffer = NULL;
	}
}

void RectElement::SetPos(float fx, float fy, float fWidth, float fHeight, float fTexLeft, float fTexRight, float fTexTop, float fTexBottom, float fAlpha)
{	
	RECT_VERTEX* pVertices = NULL;
	if( FAILED( m_pVertexBuffer->Lock( 0, 0, ( void** )&pVertices, 0 ) ) )
	{
		return;
	}

	int nAlpha = int(fAlpha * 255.f);
	m_Color = (m_Color & 0x00ffffff) | (nAlpha << 24);
	
	fy = -fy;
	fx = -fx;
	
	pVertices[0].pos = D3DXVECTOR3(fx, fy, 0.f);
	pVertices[0].color = m_Color;
	pVertices[0].ft = fTexLeft;
	pVertices[0].fv = fTexTop;

	pVertices[1].pos = D3DXVECTOR3(fx - fWidth, fy, 0.f);
	pVertices[1].color = m_Color;
	pVertices[1].ft = fTexRight;
	pVertices[1].fv = fTexTop;

	pVertices[2].pos = D3DXVECTOR3(fx, fy - fHeight, 0.f);
	pVertices[2].color = m_Color;
	pVertices[2].ft = fTexLeft;
	pVertices[2].fv = fTexBottom;

	pVertices[3].pos = D3DXVECTOR3(fx, fy - fHeight, 0.f);
	pVertices[3].color = m_Color;
	pVertices[3].ft = fTexLeft;
	pVertices[3].fv = fTexBottom;

	pVertices[4].pos = D3DXVECTOR3(fx - fWidth, fy, 0.f);
	pVertices[4].color = m_Color;
	pVertices[4].ft = fTexRight;
	pVertices[4].fv = fTexTop;

	pVertices[5].pos = D3DXVECTOR3(fx - fWidth, fy - fHeight, 0.f);
	pVertices[5].color = m_Color;
	pVertices[5].ft = fTexRight;
	pVertices[5].fv = fTexBottom;
	
	m_pVertexBuffer->Unlock();
}

void RectElement::Draw(LPDIRECT3DDEVICE9 pd3dDevice)
{
	pd3dDevice->SetTexture( 0, m_pTexture );
	pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
	pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
	pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
	pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE );
	pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
	pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE );

	pd3dDevice->SetStreamSource( 0, m_pVertexBuffer, 0, sizeof( RECT_VERTEX ) );
	pd3dDevice->SetFVF( RECT_VERTEX::dwFVF );
	pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, 2 );
}